//
//  TSBusinessFileManager.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/27.
//

class TSBusinessFileManager {
    
    /// 获取 Video 下载后保存的的文件件路径
    static var saveVideoPathURL:URL = {
        let saveRingPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("video")
        return saveRingPathURL
    }()
    
    static var saveCacheAllPathURL:URL = {
        let saveRingPathURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("cacheAll")
        return saveRingPathURL
    }()
    
    public static func generateFileName(
        urlString: String,
        fileEx:String? = nil,
    missingEx:String? = nil
    )->String?{
        guard let url = URL(string: urlString) else{
            return nil
        }
        
        var fileName = url.path.md5

        // 使用 URL 的 MD5 哈希值作为缓存文件名，附加 URL 的后缀名
        var fileExtension = ""
        if let fileEx = fileEx {
            fileExtension = fileEx
        }else{
            var missingExStr = ""
            if let missingEx = missingEx {
                missingExStr = missingEx
            }
            fileExtension = url.pathExtension.isEmpty ? missingExStr : url.pathExtension
        }

        if fileExtension.count > 0 {
            fileName = url.path.md5 + ".\(fileExtension)"
        }
         
        return fileName
    }
    
    //获取 urlstring 本地的缓存 url path
    public static func getLocalURL(
        urlString: String,
        fileEx:String? = nil,
    missingEx:String? = nil)->URL?{
        
        guard let fileName = generateFileName(urlString: urlString,fileEx:fileEx,missingEx: missingEx) else{
            return nil
        }
        
        //检查文件是否已存在于缓存中
        let ringFileURL = saveVideoPathURL.appendingPathComponent(fileName)
        if FileManager.default.fileExists(atPath: ringFileURL.path) {
            print("文件已存在于缓存中: \(ringFileURL)")
            return ringFileURL
        }
        
        let cachedFileURL = saveCacheAllPathURL.appendingPathComponent(fileName)
        if FileManager.default.fileExists(atPath: cachedFileURL.path) {
            print("文件已存在于缓存中: \(cachedFileURL)")
            return cachedFileURL
        }
        
        return nil
    }
    

}

//缓存路径
extension TSBusinessFileManager {
    
    //检查 url 对不对
    public static func generateCachesURL(
        from urlString: String,
        fileEx:String? = nil,
    missingEx:String? = nil,
        cacheDirectory:String = "cacheAll",
        completion:((String?, Error?) -> Void)? = nil
    )->URL?
    {
        guard let url = URL(string: urlString) else{
            completion?(nil, NSError(domain: "url null", code: 0))
            return nil
        }
        
        if !urlString.contains("http") && urlString.contains("/"){
            completion?(urlString.fillCachePath, nil)
            return nil
        }
        
        let fileManager = FileManager.default
        
        // 获取缓存目录下的 `cacheAll` 文件夹路径
        let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
        let cacheAllDirectory = cachesDirectory.appendingPathComponent(cacheDirectory)
        
        // 创建 `cacheAll` 文件夹（如果不存在）
        if !fileManager.fileExists(atPath: cacheAllDirectory.path) {
            do {
                try fileManager.createDirectory(at: cacheAllDirectory, withIntermediateDirectories: true, attributes: nil)
            } catch {
                completion?(nil, error)
                return nil
            }
        }
        
        
        guard let fileName = generateFileName(urlString: urlString,fileEx:fileEx,missingEx: missingEx) else{
            completion?(nil, NSError(domain: "url error", code: 0))
            return nil
        }

        let cachedFileURL = cacheAllDirectory.appendingPathComponent(fileName)
        return cachedFileURL
    }
    
    //获取 urlstring 本地的缓存 url path
    public static func getCachesURL(
        from urlString: String,
        fileEx:String? = nil,
    missingEx:String? = nil,
        cacheDirectory:String = "cacheAll")->URL?{
        
        if let cachedFileURL = generateCachesURL(
            from: urlString,
            fileEx: fileEx,
            missingEx: missingEx,
            cacheDirectory: cacheDirectory
        ){
            //检查文件是否已存在于缓存中
            if FileManager.default.fileExists(atPath: cachedFileURL.path) {
                print("文件已存在于缓存中: \(cachedFileURL)")
                return cachedFileURL
            }
        }
        
        return nil
    }
    
}
